package com.lucker.service.user;

import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.lucker.cds.model.CMUser;
import com.lucker.common.enums.CheckCodeType;
import com.lucker.common.enums.UserTokenType;
import com.lucker.common.enums.VirtualMoneyHistoryType;
import com.lucker.common.enums.VirtualMoneyType;
import com.lucker.common.request.RequestHeader;
import com.lucker.common.util.SysRestrictionsConfigType;
import com.lucker.ds.mapper.BaseCustomMapper;
import com.lucker.ds.model.MUser;
import com.lucker.ds.model.SysCheckCode;
import com.lucker.ds.model.SysRestrictionsConfig;
import com.lucker.ds.model.UserToken;
import com.lucker.framework.constant.ResponseBaseModel;
import com.lucker.framework.constant.ResponseResultModel;
import com.lucker.framework.constant.UserRoleType;
import com.lucker.framework.exception.BaseServiceException;
import com.lucker.service.BaseServiceImpl;
import com.lucker.service.checkcode.SysCheckCodeService;
import com.lucker.service.sys.SysRestrictionsConfigService;

@Service
public class MuserServiceImpl extends BaseServiceImpl<MUser, CMUser, Long> implements MuserService{
	
	@Autowired
	private UserTokenService userTokenService;
	
	@Autowired
	private UserVirtualMoneyService userVirtualMoneyService;
	
	@Autowired
	private SysRestrictionsConfigService sysRestrictionsConfigService;
	
	@Autowired
	private SysCheckCodeService sysCheckCodeService;
	
	@Override
	public BaseCustomMapper<CMUser, Long> getCustomMapper() {
		return null;
	}
    
	@Transactional
	public int registerUser(MUser muser,String code) { 
		if(StringUtils.isBlank(muser.getUserName())) {
			throw new BaseServiceException("用户手机号不能为空");
		}
		if(muser.getRoleId() == null) {
			throw new BaseServiceException("用户角色不能为空");
		}
		if(StringUtils.isBlank(code)) {
			throw new BaseServiceException("缺少短信验证码");
		}
		
		
		//check checkcode begin
//		SysCheckCode querySysCheckCode = new SysCheckCode();
//		querySysCheckCode.setMobile(muser.getUserName());
//		querySysCheckCode.setCode(code);
//		querySysCheckCode.setType(1);
//		querySysCheckCode.setStatus(Constant.DATA_STATUS_EFFECTIVE);
//		querySysCheckCode.orderByCreateTime(false);
//		
//		List<SysCheckCode> _syscheckcode_list = sysCheckCodeService.queryAll(querySysCheckCode);
//		if(CollectionUtils.isEmpty(_syscheckcode_list)) {
//			throw new BaseServiceException("短信验证码错误");
//		}
//		SysCheckCode _sysCheckCode = _syscheckcode_list.get(0);
//		Date now = new Date();
//		
//		if((now.getTime() - _sysCheckCode.getCreateTime().getTime() ) > (1000 * 10 * 60)) {
//			throw new BaseServiceException("短信验证码超时，请重新获取短信验证码");
//		}
//		_sysCheckCode.setStatus(0);
//		sysCheckCodeService.modify(_sysCheckCode, false);		
		// check checkcode end
		
		
		if(sysCheckCodeService.checkCode(muser.getUserName(), code, CheckCodeType.REG_TYPE_SMS_CODE)) {
			String nickName = "彩友" + (int)((Math.random()*9+1)*1000000);
			muser.setNickName(nickName);
			muser.setIsDelete(Boolean.FALSE);
			muser.setIsFreeze(Boolean.FALSE);
			muser.setRoleId(UserRoleType.DEFUALT_ROLE);
			
			int ret = this.getBaseMapper().insert(muser);
			
			SysRestrictionsConfig _sysRestrictionsConfig = new SysRestrictionsConfig();
			_sysRestrictionsConfig.setType(SysRestrictionsConfigType.GIVE_VIRTUALMONEY_AMOUNT);
			_sysRestrictionsConfig.setStatus(1);
			List<SysRestrictionsConfig> _list = sysRestrictionsConfigService.queryAll(_sysRestrictionsConfig);
			
			//注册是否送用户虚拟币
			
			if(CollectionUtils.isNotEmpty(_list) && _list.get(0).getExperience() > 0) {
				userVirtualMoneyService.addUserVirtualMoney(muser.getId(), Long.valueOf(_list.get(0).getExperience()), VirtualMoneyType.virtualmoney , VirtualMoneyHistoryType.reg_gift, String.valueOf(muser.getId()));
			}
			
			//赠送逻辑
			return ret;
		}else {
			return 0;
		}
		
	}
	
	
	public MUser getUserByUserNamePass(String userName) {
		MUser _u = new MUser();
		_u.setUserName(userName);
		//_u.setIsDelete(Boolean.FALSE);
		//_u.setIsFreeze(Boolean.FALSE);
		List<MUser> _list = this.getBaseMapper().selectAll(_u);
		if(org.apache.commons.collections.CollectionUtils.isEmpty(_list)) {
			return null;
		}else {
			if(_list.size() > 1) {
				this.getLOGGER().error("根据{}这个手机号，查询到多条用户数据! ", userName);
				throw new BaseServiceException("登录异常，请稍后再试!");
			}else {
				if(_list.get(0).getIsDelete()) {
					throw new BaseServiceException("登录异常，账户已被禁用!");
				}
				if(_list.get(0).getIsFreeze()) {
					throw new BaseServiceException("登录异常，账户已被冻结!");
				}
				return _list.get(0);
			}
		}
		
	}
	
	public CMUser login(MUser user,RequestHeader requestHeader) {
		if(requestHeader == null) {
			throw new BaseServiceException("参数异常");
		}
		if(StringUtils.isBlank(requestHeader.getAppType())) {
			throw new BaseServiceException("参数异常 appType");
		}
		if(user == null) {
			throw new BaseServiceException("参为异常, user为空");
		}
		if(StringUtils.isBlank(user.getUserName())) {
			throw new BaseServiceException("用户手机号不能为空");
		}
		if(StringUtils.isBlank(user.getPassword())) {
			throw new BaseServiceException("密码不能为空");
		}
		
		MUser _loginUser = this.getUserByUserNamePass(user.getUserName());
		
		if(_loginUser == null) {
			throw new BaseServiceException("用户不存在");
		}
		
		
		CMUser loginUser = new CMUser(); 
		if(StringUtils.equals(user.getPassword(), _loginUser.getPassword())) {
			try {
				BeanUtils.copyProperties(loginUser, _loginUser);
			} catch (IllegalAccessException e) {
				getLOGGER().error("用户登录返回值转换错误 信息: {}" , e);
				throw new BaseServiceException("用户登录返回值转换错误");
			} catch (InvocationTargetException e) {
				getLOGGER().error("用户登录返回值转换错误 信息: {}" , e);
				throw new BaseServiceException("用户登录返回值转换错误");
			} 
			
			UserToken utk = userTokenService.reSetUserToken(_loginUser.getId(), UserTokenType.USER_TOKEN_LOGIN, requestHeader.getAppType());
			loginUser.setUserToken(utk.getUserToken());
			loginUser.setPassword("fuck you!");
			
			return loginUser;
		}else {
			throw new BaseServiceException("密码错误");
			
		}
	}
	
	
	public ResponseEntity<?> checkCodeLogin(SysCheckCode checkCode, RequestHeader header){
		
		boolean isLogin = sysCheckCodeService.checkCode(checkCode.getMobile(), checkCode.getCode(), CheckCodeType.LOGIN_SMS_CODE);
		
		if(isLogin) {
			MUser user = queryById(checkCode.getUserId());
			UserToken token = userTokenService.reSetUserToken(user.getId(), UserTokenType.USER_TOKEN_LOGIN, header.getAppType());
			CMUser loginUser = new CMUser(); 
			try {
				BeanUtils.copyProperties(loginUser, user);
			} catch (Exception e) {
				getLOGGER().error("用户验手机证码登录返回值转换错误 信息: {}" , e);
				return new ResponseEntity<>(new ResponseBaseModel(29002, "登录失败,对象转换错误 !" ), HttpStatus.OK);
			}
			loginUser.setUserToken(token.getUserToken());
			loginUser.setPassword("");
			return new ResponseEntity<>(new ResponseResultModel<CMUser>(loginUser),HttpStatus.OK);
		}else{
			return new ResponseEntity<>(new ResponseBaseModel(29002, "登录失败" ), HttpStatus.OK);
		}
	}
	
	
	

}
